<template>
  <div>
    <!-- title -->
    <h2>用户管理</h2>

    <Divider />

    <Form ref="form" :model="form" inline>
      <FormItem>
        <Input type="text" v-model="form.userNo"
               style="width: 200px;" placeholder="工号"/>
      </FormItem>
      <FormItem>
        <Input type="text" v-model="form.name"
               style="width: 200px;" placeholder="姓名"/>
      </FormItem>
      <FormItem>
        <Input type="text" v-model="form.mobile"
               style="width: 200px;" placeholder="手机号"/>
      </FormItem>
      <FormItem>
        <Cascader v-model="form.departmentIds" placeholder="部门"
                  :data="departments" change-on-select></Cascader>
      </FormItem>
      <FormItem class="button-container">
        <Button type="primary" icon="ios-search"
                @click="search">查询</Button>
        <Button icon="ios-trash"
                @click="reset">清空</Button>
      </FormItem>
    </Form>

    <Divider />

    <div class="button-container margin-bottom-8">
      <Button v-if="hasPermissionEdit"
              type="primary" icon="md-add"
              @click="openCreateModal">添加</Button>
    </div>

    <Table stripe
           :columns="table.columns"
           :data="table.data"
           :loading="table.loading">
      <template slot-scope="{ row }" slot="disabled">
        <Tag :color="row.disabled ? 'red' : 'blue'">
          {{ row.disabled ? '禁用' : '启用' }}
        </Tag>
      </template>

      <template slot-scope="{ row }" slot="roles">
        <Tag v-for="(item, index) in row.roles"
             color="blue" :key="index">
          {{ item.role }} - {{ item.description }}
        </Tag>
      </template>

      <template slot-scope="{ row }" slot="departments">
        <Tag v-for="(item, index) in row.departments"
             color="blue" :key="index">
          {{ item.name }}
        </Tag>
      </template>

      <template slot="action" slot-scope="{ row }">
        <div class="button-container">
          <Button v-if="hasPermissionEdit"
                  type="primary" size="small"
                  @click="openUpdateModal(row.id)">编辑</Button>
          <Button v-if="hasPermissionUpdatePassword"
                  type="primary" size="small"
                  @click="openUpdatePasswordModal(row.id)">修改密码</Button>
          <Button v-if="hasPermissionDisabled"
                  :type="row.disabled ? 'primary' : 'error'"
                  size="small"
                  @click="updateDisabled(row.id, !row.disabled)">
            {{ row.disabled ? '启用' : '禁用' }}
          </Button>
          <Button v-if="hasPermissionDelete"
                  type="error" size="small"
                  @click="delUser(row.id)">删除</Button>
        </div>
      </template>
    </Table>

    <div class="page-container">
      <Page :current="page.current" :total="page.total"
            :page-size="page.size"
            show-elevator show-sizer show-total
            @on-change="handleChangePage"
            @on-page-size-change="handleChangePageSize"/>
    </div>

    <Create ref="createModal" @success="search"></Create>
    <Update ref="updateModal" @success="initData"></Update>
    <UpdatePassword ref="updatePasswordModal" @success="initData"></UpdatePassword>
  </div>
</template>

<script>
import { getUsers, deleteUser, disabledUser } from '../../../apis/system/user';
import { departmentTree } from '../../../apis/system/department';
import SystemUtil from '../../../utils/systemUtil';

import Create from './components/create.vue';
import Update from './components/update.vue';
import UpdatePassword from './components/updatePassword.vue';

export default {
  name: 'user',
  components: {
    Create,
    Update,
    UpdatePassword
  },
  data() {
    const columns = [
      {
        title: '工号',
        key: 'userNo'
      },
      {
        title: '姓名',
        key: 'name'
      },
      {
        title: '手机号',
        key: 'mobile'
      },
      {
        title: '角色',
        slot: 'roles'
      },
      {
        title: '部门',
        slot: 'departments'
      },
      {
        title: '是否禁用',
        slot: 'disabled'
      },
    ];

    if (this.$permission.hasPermissions(['system:user:edit', 'system:user:delete',
      'system:user:updatePassword', 'system:user:disabled'])) {
      columns.push({
        title: '操作',
        slot: 'action',
        width: 300
      });
    }

    return {
      form: {
        userNo: '',
        name: '',
        mobile: '',
        departmentIds: []
      },
      table: {
        columns,
        data: [],
        loading: false,
      },
      page: {
        total: 0,
        current: 1,
        size: 10,
      },
      departments: [],
    };
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      this.initDepartments();
      this.initData();
    },
    initDepartments() {
      departmentTree(undefined, (responseData) => {
        this.departments = SystemUtil.getDepartments(responseData);
      });
    },
    initData() {
      this.table.loading = true;

      const departmentId = this.form.departmentIds && this.form.departmentIds.length > 0
        ? this.form.departmentIds[this.form.departmentIds.length - 1] : undefined;
      getUsers({
        userNo: this.form.userNo,
        name: this.form.name,
        mobile: this.form.mobile,
        departmentId,
        page: true,
        current: this.page.current,
        size: this.page.size
      }, (responseData) => {
        this.table.loading = false;

        this.table.data = responseData.records;
        this.page.total = Number(responseData.total);
      }, () => {
        this.table.loading = false;
      });
    },
    search() {
      this.page.current = 1;
      this.initData();
    },
    reset() {
      this.form = {
        userNo: '',
        name: '',
        mobile: '',
        departmentIds: []
      };
      this.page.current = 1;
      this.initData();
    },
    handleChangePage(current) {
      this.page.current = current;
      this.initData();
    },
    handleChangePageSize(size) {
      this.page.size = size;
      this.page.current = 1;
      this.initData();
    },
    openCreateModal() {
      this.$refs.createModal.openModal();
    },
    openUpdateModal(id) {
      this.$refs.updateModal.openModal(id);
    },
    openUpdatePasswordModal(id) {
      this.$refs.updatePasswordModal.openModal(id);
    },
    updateDisabled(id, disabled) {
      this.$Modal.confirm({
        title: '提示',
        content: `此操作将${disabled ? '禁用' : '启用'}该用户，是否继续？`,
        loading: true,
        onOk: () => {
          disabledUser(id, {
            disabled
          }, () => {
            this.$Modal.remove();
            this.$Message.success(`${disabled ? '禁用' : '启用'}成功`);
            this.initData();
          });
        }
      });
    },
    delUser(id) {
      this.$Modal.confirm({
        title: '提示',
        content: '此操作将永久删除该数据，是否继续？',
        loading: true,
        onOk: () => {
          deleteUser(id, () => {
            this.$Modal.remove();
            this.$Message.success('删除成功');
            this.initData();
          });
        }
      });
    }
  },
  computed: {
    hasPermissionEdit() {
      return this.$permission.hasPermissions(['system:user:edit']);
    },
    hasPermissionUpdatePassword() {
      return this.$permission.hasPermissions(['system:user:updatePassword']);
    },
    hasPermissionDisabled() {
      return this.$permission.hasPermissions(['system:user:disabled']);
    },
    hasPermissionDelete() {
      return this.$permission.hasPermissions(['system:user:delete']);
    },
  },
};
</script>

<style scoped>

</style>
